﻿using System.Collections.Generic;

namespace EFMLEditor.Internal
{
    using System.IO;
    using System.Linq;
    using System.Xml;

    public class BinaryWindowBuilder
    {
        public static Document[] Compile(Document[] nonbinary)
        {
            var r = new List<Document>();
            var c = "";

            var i = 0;
            while(i < nonbinary.Length)
            {
                if(istGerade(i))
                {
                    var windowI = i - 1;
                    var codeI = i;

                    if (!nonbinary[codeI].Name.EndsWith(".string"))
                    {
                        var doc = new XmlDocument();
                        doc.LoadXml(nonbinary[codeI].Value);
                        var head = doc.GetElementsByTagName("head")[0];
                        var script = doc.CreateElement("script");
                        script.InnerText = nonbinary[windowI].Value;
                        head.AppendChild(script);

                        var ms = new MemoryStream();
                        doc.Save(ms);

                        r.Add(
                            new Document
                                {
                                    Name = nonbinary[windowI].Name,
                                    Value = System.Text.Encoding.ASCII.GetString(ms.ToArray())
                                });
                    }
                }
                i += 1;
            }

            return r.ToArray();
        }
        private static bool istGerade(int Zahl)
        {
            return Zahl % 2 == 0;
        }
    }
}
